package com.example.mybatisplusdemo.Controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.mybatisplusdemo.Result.Result;
import com.example.mybatisplusdemo.Service.AdminService;
import com.example.mybatisplusdemo.Service.EmployeeService;
import com.example.mybatisplusdemo.pojo.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;

@RestController
@RequestMapping("/api")
@CrossOrigin
public class EmployeeController {
    @Autowired
    EmployeeService employeeService;
    @Autowired
    AdminService adminService;
    /**
     * 取得所有的员工列表
     * @return list
     */
    @RequestMapping(value = "/getemployees",method = RequestMethod.GET)
    public Result getemployees(@RequestParam("token") String token){
        if (!adminService.checktoken(token)) {
            return new Result(400,"没有权限！");
        }
        List<Employee> employees = employeeService.list();
        return new Result(200,"请求成功",employees);
    }

    /**
     * 添加新的员工
     * @param employee
     * @return result
     */
    @RequestMapping(value = "/addemployee/{token}",method = RequestMethod.POST)
    public Result addemployee(@RequestBody Employee employee,@PathVariable("token") String token){
        if (!adminService.checktoken(token)) {
            return new Result(400,"没有权限！");
        }
//       判断输入的值是否为空
        if (employee.getUsername() == null ){
            return new Result(400,"用户名为空！");
        }
        else if (employee.getEmail() == null ){
            return new Result(400,"邮箱为空！");
        }
        else if (employee.getAge() == null ){
            return new Result(400,"年龄为空！");
        }
//      判断用户名或邮箱是否存在
        QueryWrapper<Employee> usernameQueryWrapper = new QueryWrapper<>();
        usernameQueryWrapper.eq("username",employee.getUsername());
        int usernamecount = employeeService.count(usernameQueryWrapper);
        QueryWrapper<Employee> emailQueryWrapper = new QueryWrapper<>();
        emailQueryWrapper.eq("email",employee.getEmail());
        int emailcount = employeeService.count(emailQueryWrapper);
        if (usernamecount != 0){
            return new Result(400,"用户名已经被使用！");
        }else if(emailcount != 0){
            return new Result(400,"邮箱已经被使用！");
        }
//        进入注册流程
        Employee newEmployee = new Employee();
        newEmployee.setUsername(employee.getUsername());
        newEmployee.setAge(employee.getAge());
        newEmployee.setEmail(employee.getEmail());
        employeeService.save(newEmployee);
        return new Result(200,"添加成功",newEmployee);
    }
}
